<template>
  <el-dialog
    :visible="opetatorDialog"
    :before-close="handleClose"
    :show-close="true"
    :close="handleClose"
    class="small-common-dialog-size operator-dialog"
  >
    <Title title="关联供应商" style="margin-bottom:12px" font-size="16px"/>
    <span class="tip">关联供应商后即可对该达人发起询单</span>
    <el-form class="form" label-position="left" label-width="90px">
      <el-form-item
        style="margin-bottom:0"
        label="供应商名称">
        <select-with-user-load
          ref="selectWithUserLoad"
          v-model="supplierId"
          :default-list="defaultList"
          :hide-select-list="supplierList"
          :loadmore-method="getSupplier({ onlyChannel: true })"
          :clearable="true"
          :add-new="true"
          :collapse-tags="false"
          key-name="supplierId"
          label-name="supplierName"
          multiple
          open-tool-tip
          placeholder="请选择"
          extend-class="image"
          filterable
          @addNewClick="goCreateSupplier"
          @visibleChange="visibleChange"
        />
      </el-form-item>
      <el-form-item label="">
        <el-checkbox v-model="isSync" style="color: #333333">将用户信息同步至供应商信息</el-checkbox>
        <el-checkbox v-model="isEnable" style="color: #333333">关联后自动启用用户</el-checkbox>
      </el-form-item>
    </el-form>
    <div class="center">
      <el-button
        :disabled="loading"
        :loading="loading"
        type="primary"
        size="small"
        class="ok submit-btn"
        @click="relateSupplier"
      >
        确定
      </el-button>
      <el-button
        class="back-btn cancel-btn-style"
        type="info"
        size="small"
        @click="handleClose"
      >关闭</el-button>
    </div>
    <relatedDialog ref="relatedDialog" @close="close" />
  </el-dialog>
</template>
<script>
import { relateSupplier, supplierRelated } from '@/api/flyUser';
import { getSupplierList } from '@/api/select';
import Title from '@/components/Title';
import SelectWithUserLoad from '@/components/Common/selectWithUserLoad';
import { enter2Br } from '@/utils/string';
import relatedDialog from './relatedDialog';

export default {
  components: { Title, SelectWithUserLoad, relatedDialog },
  data() {
    return {
      id: '',
      supplierId: [],
      supplierList: [], // 默认选中的关联供应商
      isSync: false,
      opetatorDialog: false,
      loading: false,
      isEnable: true,
      defaultList: []
    };
  },
  methods: {
    openDialog(id, supplierList, userName) {
      this.id = id;
      this.supplierId = supplierList.map(item => item.supplierId);
      this.supplierList = supplierList;
      if (userName) {
        const params = {
          page: 1,
          perPage: 10,
          onlyChannel: true,
          supplierName: userName
        };
        getSupplierList(params).then(res => {
          if (res.code === 200 && res.data) {
            const { items } = res.data;
            if (!items.length) {
              this.$message({ type: 'warning', message: '不存在包含该用户姓名的供应商' });
            }
            this.defaultList = items;
            setTimeout(() => {
              this.$refs['selectWithUserLoad'].$refs['userSelect'].focus();
            }, 200);
          }
        }).catch(err => {
          console.error(err);
          this.$message.error(err.message);
        });
      }
      this.opetatorDialog = true;
    },
    handleClose() {
      this.isSync = false;
      this.supplierId = [];
      this.supplierList = [];
      this.defaultList = [];
      this.opetatorDialog = false;
    },
    visibleChange(e) {
      if (!e && this.$refs['selectWithUserLoad']) {
        this.$refs['selectWithUserLoad'].getListData();
      }
    },
    beforeRelated(cb) {
      const params = {
        ids: this.supplierId.join(',')
      };
      supplierRelated(params).then(res => {
        if (res.data && res.data.length > 0) {
          this.$refs['relatedDialog'].openDialog(res.data);
          this.loading = false;
        } else {
          cb && cb();
        }
      }, _ => {
        this.loading = false;
      }).catch(err => {
        console.error(err.message);
        this.loading = false;
      });
    },
    close() {
      this.loading = false;
    },
    relateSupplier() {
      if (!Array.isArray(this.supplierId) || !this.supplierId.length) {
        // this.$message.error('请选择要关联的供应商');
        // return;
        this.isSync = false;
        // this.isEnable = false;
      }
      this.loading = true;
      this.beforeRelated(() => {
        const data = {
          id: this.id,
          supplierId: this.supplierId,
          isSync: this.isSync,
          isEnable: this.isEnable
        };
        relateSupplier(data).then(res => {
          this.loading = false;
          if (res.code !== 200) {
            this.$message.error(res.message);
            return;
          }
          this.$message.success(`关联成功`);
          this.$emit('succese');
        }).catch(err => {
          console.log(err);
          this.$confirm(enter2Br(err.message), '', {
            confirmButtonText: '确定',
            showCancelButton: false,
            showClose: true,
            type: 'warning',
            center: true,
            iconClass: 'charge-icon',
            customClass: 'message-box',
            dangerouslyUseHTMLString: true
          }).then(() => {
          });
          this.loading = false;
        });
        this.handleClose();
      });
    },
    getSupplier() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          getSupplierList({ onlyChannel: true, ...params }).then(res => {
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    goCreateSupplier() {
      const routeUrl = this.$router.resolve({
        name: 'supplierManage',
        query: {
          toCreate: 1
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
.operator-dialog{
  &::v-deep {
    .el-dialog__body{
      padding: 16px 24px 24px !important;
    }
    .el-form-item__label{
      padding: 0 12px 0 8px;
    }
    .filterableSelect{
      width: 90%;
    }
    .ps--active-y {
      padding-right: 10%;
    }
    .el-select__input {
      min-width: 80px;
    }
    .el-select__tags-text {
      color: #406EFF !important;
    }
  }
  .el-tag.el-tag--info {
    background-color: #EFF3FB !important;
  }
  .form{
    margin-top: 17px;
    &::v-deep {
      .el-tag.el-tag--info{
        display: flex;
        align-items: center;
      }
      .el-select .el-tag__close.el-icon-close{
        right: 0;
      }
      .el-select__tags-text{
        display: inline-block;
        max-width: 160px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }
  .center{
    display: flex;
    justify-content: center;
  }
  .tip{
    color: #999999;
    font-size: 14px;
    margin-left: 8px;
  }
}
</style>
